<?php
/**
 * Created by jinqiang on 2024/10/28 13:48.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Produce;


use App\Http\Models\Mysql\SsyProcessingListDetailsQtLogTable;
use App\Http\Models\Mysql\SsyProcessingListDetailsQcReasonTable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

class WCheckService
{
    private function getQcTime($type){
        $data = [
            "today" => [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')],
            "yesterday" => [date('Y-m-d 00:00:00', strtotime("- 1 day")), date('Y-m-d 23:59:59', strtotime("- 1 day"))],
            "day_7" => [date('Y-m-d 00:00:00', strtotime("- 7 day")), date('Y-m-d 23:59:59')],
            "current_month" => [date('Y-m-01 00:00:00'), date('Y-m-d 23:59:59')],
            "last_month" => [date('Y-m-01 00:00:00', strtotime("- 1 month")), date('Y-m-t 23:59:59', strtotime("- 1 month"))],
            "current_year" => [date('Y-01-01 00:00:00'), date('Y-m-t 23:59:59')],
            "last_year" => [date('Y-01-01 00:00:00', strtotime("- 1 year")), date('Y-12-31 23:59:59', strtotime('- 1 year'))]
        ];
        return $data[$type];
    }

    public function passSearch($param)
    {
        $field = $param['tab'] == 'factory' ? ['factory_name'] : ['processing_code', 'type_no', 'factory_name'];
        $conn = (new SsyProcessingListDetailsQtLogTable())->select($field)->whereBetween('qc_date', $param['qc_date']);
        if($param['factory_name'] ?? ""){
            $conn = $conn->where('factory_name', $param['factory_name']);
        }
        if($param['processing_code'] ?? ""){
            $conn = $conn->where('processing_code', $param['processing_code']);
        }
        if($param['type_no'] ?? ""){
            $conn = $conn->where('type_no', $param['type_no']);
        }
        $res = $conn->groupBy($field)->paginate((Int)$param['limit'])->toArray();
        foreach ($res['data'] as &$item){
            $field = $param['tab'] == 'factory' ? 'factory_name' : 'processing_code';
            //总数
            $totalNum = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_date', $param['qc_date'])->where($field, $item[$field])->count();
            //合格
            $passNum = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_date', $param['qc_date'])->where($field, $item[$field])->where('status', 1)->count();
            //不合格
            $unPassNum = $totalNum - $passNum;
            //合格率
            $rate = !empty($totalNum) ? round($passNum / $totalNum * 100, 2) : 0;
            $item['total_num'] = $totalNum;
            $item['pass_num'] = $passNum;
            $item['un_pass_num'] = $unPassNum;
            $item['rate'] = $rate;
        }
        unset($item);
        return ['data' => $res['data'], 'total' => $res['total']];
    }

    public function rosterSearch($param)
    {
        $conn = (new SsyProcessingListDetailsQtLogTable())->select(['qc_user','user_id'])->whereBetween('qc_date', $param['qc_date']);
        if($param['qc_user'] ?? ""){
            $conn = $conn->where('qc_user', $param['qc_user']);
        }
        $res = $conn->groupBy(['qc_user','user_id'])->paginate((Int)$param['limit'])->toArray();
        foreach ($res['data'] as &$item){
            //总数
            $totalNum = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_date', $param['qc_date'])->where('user_id', $item['user_id'])->count();
            //合格
            $passNum = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_date', $param['qc_date'])->where('user_id', $item['user_id'])
                ->where('status', 1)->count();
            //不合格
            $unPassNum = $totalNum - $passNum;
            //合格率
            $rate = !empty($totalNum) ? round($passNum / $totalNum * 100, 2) : 0;
            $item['total_num'] = $totalNum;
            $item['pass_num'] = $passNum;
            $item['un_pass_num'] = $unPassNum;
            $item['rate'] = $rate;
        }
        unset($item);
        return ['data' => $res['data'], 'total' => $res['total']];
    }

    public function search($param)
    {
        $conn = new SsyProcessingListDetailsQtLogTable();
        if($param['user_id'] ?? ""){
            $conn = $conn->where('user_id', (Int)$param['user_id']);
        }
        if(!empty($param['qc_time'])){
            $conn = $conn->whereBetween('qc_time', $this->getQcTime($param['qc_time']));
        }
        if(!empty($param['qc_date'])){
            $conn = $conn->whereBetween('qc_date', $param['qc_date']);
        }
        if($param['type_no'] ?? ""){
            $conn = $conn->where('type_no', $param['type_no']);
        }
        if($param['number'] ?? ""){
            $conn = $conn->where('number', $param['number']);
        }
        if(isset($param['status']) && $param['status'] != ""){
            $conn = $conn->where('status', (Int)$param['status']);
        }
        $res = $conn->orderBy('qc_time', 'desc')->orderBy('id', 'desc')->paginate((Int)$param['limit'], "*", "page", (Int)$param['page'])->toArray();
        foreach ($res['data'] as &$item){
            $item['qc_img'] = unserialize($item['qc_img']);
        }
        unset($item);
        return [
            'data' => $res['data'],
            'total' => $res['total'],
            'detail' => $param['all'] ? $this->unpassDetail($param['qc_time']) : []
        ];
    }

    //不合格问题明细
    public function unpassDetail($qcType)
    {
        $cacheKey = "QT_STATISTIC_PANEL_{$qcType}";
        $res = Cache::get($cacheKey);
        if(!empty($res)){
            return $res;
        }
        $qcTime = $this->getQcTime($qcType);
        $reasonList = (new SsyProcessingListDetailsQcReasonTable())->where('status', 0)->where('type', 1)->get(['title'])->toArray();
        $reasonList = array_column($reasonList, 'title');
        $data = [];
        $t = microtime(true);
        foreach ($reasonList as $reason) {
            $data[] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $qcTime)->where('status', 0)->where('reason_title', $reason)->count();
        }
        $res = [$reasonList, $data];
        //数据缓存30分钟
        Cache::put($cacheKey, $res, Carbon::now()->addMinutes(30));
        return $res;
    }

    //qc看板
    public function panel()
    {
        $cacheKey = "QT_STATISTIC_PANEL";
        $res = Cache::get($cacheKey);
        if(!empty($res)){
            return $res;
        }
        $res = [];
        //今日总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('today');
        $res['today']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->count();
        $res['today']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->where('status', 1)->count();
        $res['today']['un_pass_num'] = $res['today']['total_num'] - $res['today']['pass_num'];
        $res['today']['rate'] = !empty($res['today']['total_num']) ? round($res['today']['pass_num'] / $res['today']['total_num'] * 100, 2) : 0;
        //昨日总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('yesterday');
        $res['yesterday']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->count();
        $res['yesterday']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->where('status', 1)->count();
        $res['yesterday']['un_pass_num'] = $res['yesterday']['total_num'] - $res['yesterday']['pass_num'];
        $res['yesterday']['rate'] = !empty($res['yesterday']['total_num']) ? round($res['yesterday']['pass_num'] / $res['yesterday']['total_num'] * 100, 2) : 0;
        //近7日总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('day_7');
        $res['day_7']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->count();
        $res['day_7']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->where('status', 1)->count();
        $res['day_7']['un_pass_num'] = $res['day_7']['total_num'] - $res['day_7']['pass_num'];
        $res['day_7']['rate'] = !empty($res['day_7']['total_num']) ? round($res['day_7']['pass_num'] / $res['day_7']['total_num'] * 100, 2) : 0;
        //本月总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('current_month');
        $res['current_month']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->count();
        $res['current_month']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->where('status', 1)->count();
        $res['current_month']['un_pass_num'] = $res['current_month']['total_num'] - $res['current_month']['pass_num'];
        $res['current_month']['rate'] = !empty($res['current_month']['total_num']) ? round($res['current_month']['pass_num'] / $res['current_month']['total_num'] * 100, 2) : 0;
        //上一个月总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('last_month');
        $res['last_month']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->count();
        $res['last_month']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->where('status', 1)->count();
        $res['last_month']['un_pass_num'] = $res['last_month']['total_num'] - $res['last_month']['pass_num'];
        $res['last_month']['rate'] = !empty($res['last_month']['total_num']) ? round($res['last_month']['pass_num'] / $res['last_month']['total_num'] * 100, 2) : 0;
        //今年总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('current_year');
        $res['current_year']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->count();
        $res['current_year']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->where('status', 1)->count();
        $res['current_year']['un_pass_num'] = $res['current_year']['total_num'] - $res['current_year']['pass_num'];
        $res['current_year']['rate'] = !empty($res['current_year']['total_num']) ? round($res['current_year']['pass_num'] / $res['current_year']['total_num'] * 100, 2) : 0;
        //去年总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('last_year');
        $res['last_year']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->count();
        $res['last_year']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $dateTime)->where('status', 1)->count();
        $res['last_year']['un_pass_num'] = $res['last_year']['total_num'] - $res['last_year']['pass_num'];
        $res['last_year']['rate'] = !empty($res['last_year']['total_num']) ? round($res['last_year']['pass_num'] / $res['last_year']['total_num'] * 100, 2) : 0;

        //获取近7日的数据
        for($i = 7; $i >= 1; $i--){
            $qcDate = [
                date('Y-m-d 00:00:00', strtotime("- {$i} day")),
                date('Y-m-d 23:59:59', strtotime("- {$i} day"))
            ];
            $totalNum = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $qcDate)->count();
            $passNum = (new SsyProcessingListDetailsQtLogTable())->whereBetween('qc_time', $qcDate)->where('status', 1)->count();
            $res['week'][date('Y-m-d', strtotime($qcDate[0]))] = [
                'total_num' => $totalNum,
                'pass_num' => $passNum,
                'un_pass_num' => $totalNum - $passNum,
                'rate' => !empty($totalNum) ? round($passNum / $totalNum * 100, 2) : 0
            ];
        }
        $res['week'][date('Y-m-d')] = $res['today'];
        //数据缓存60分钟
        Cache::put($cacheKey, $res, Carbon::now()->addMinutes(60));
        return $res;
    }

    public function rosterStatistic($userId)
    {
        $cacheKey = "QT_STATISTIC_ROSTER_{$userId}";
        $res = Cache::get($cacheKey);
        if(!empty($res)){
            return $res;
        }
        $res = [];
        //今日总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('today');
        $res['today']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)->count();
        $res['today']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)->where('status', 1)->count();
        $res['today']['un_pass_num'] = $res['today']['total_num'] - $res['today']['pass_num'];
        $res['today']['rate'] = !empty($res['today']['total_num']) ? round($res['today']['pass_num'] / $res['today']['total_num'] * 100, 2) : 0;
        //昨日总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('yesterday');
        $res['yesterday']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)->count();
        $res['yesterday']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)->where('status', 1)->count();
        $res['yesterday']['un_pass_num'] = $res['yesterday']['total_num'] - $res['yesterday']['pass_num'];
        $res['yesterday']['rate'] = !empty($res['yesterday']['total_num']) ? round($res['yesterday']['pass_num'] / $res['yesterday']['total_num'] * 100, 2) : 0;
        //近7日总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('day_7');
        $res['day_7']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)->count();
        $res['day_7']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)->where('status', 1)->count();
        $res['day_7']['un_pass_num'] = $res['day_7']['total_num'] - $res['day_7']['pass_num'];
        $res['day_7']['rate'] = !empty($res['day_7']['total_num']) ? round($res['day_7']['pass_num'] / $res['day_7']['total_num'] * 100, 2) : 0;
        //本月总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('current_month');
        $res['current_month']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)->count();
        $res['current_month']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)->where('status', 1)->count();
        $res['current_month']['un_pass_num'] = $res['current_month']['total_num'] - $res['current_month']['pass_num'];
        $res['current_month']['rate'] = !empty($res['current_month']['total_num']) ? round($res['current_month']['pass_num'] / $res['current_month']['total_num'] * 100, 2) : 0;
        //上一个月总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('last_month');
        $res['last_month']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)->count();
        $res['last_month']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)->where('status', 1)->count();
        $res['last_month']['un_pass_num'] = $res['last_month']['total_num'] - $res['last_month']['pass_num'];
        $res['last_month']['rate'] = !empty($res['last_month']['total_num']) ? round($res['last_month']['pass_num'] / $res['last_month']['total_num'] * 100, 2) : 0;
        //今年总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('current_year');
        $res['current_year']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)->count();
        $res['current_year']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)
            ->where('status', 1)->count();
        $res['current_year']['un_pass_num'] = $res['current_year']['total_num'] - $res['current_year']['pass_num'];
        $res['current_year']['rate'] = !empty($res['current_year']['total_num']) ? round($res['current_year']['pass_num'] / $res['current_year']['total_num'] * 100, 2) : 0;
        //去年总数、合格、不合格、合格率
        $dateTime = $this->getQcTime('last_year');
        $res['last_year']['total_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)->count();
        $res['last_year']['pass_num'] = (new SsyProcessingListDetailsQtLogTable())->where('user_id', $userId)->whereBetween('qc_time', $dateTime)->where('status', 1)->count();
        $res['last_year']['un_pass_num'] = $res['last_year']['total_num'] - $res['last_year']['pass_num'];
        $res['last_year']['rate'] = !empty($res['last_year']['total_num']) ? round($res['last_year']['pass_num'] / $res['last_year']['total_num'] * 100, 2) : 0;
        //数据缓存30分钟
        Cache::put($cacheKey, $res, Carbon::now()->addMinutes(30));
        return $res;
    }
}
